<?php

namespace App\Http\Controllers\Index;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class ShopcartController extends Controller
{
    // 购物车
    public function udai_shopcart(){
    	$goods=DB::table('shopcart')->join('goodssize','shopcart.sid','=','goodssize.id')->join('goods','goodssize.gid','=','goods.id')->where('uid',session('uid'))->select('shopcart.id','name','goods.img','price','color','size','num')->get();
    	return view('index/Shopcart/udai_shopcart',['goods'=>$goods]);
    }

    // 添加到购物车
    public function shopcart_insert(Request $request){
    	// dd($request->all());
    	$sid=DB::table('goodssize')->where([['gid',$request->gid],['color',$request->color],['size',$request->size]])->value('id');
    	if(DB::table('shopcart')->insert(['uid'=>$request->uid,'sid'=>$sid,'num'=>$request->num])){
    		return 1;
    	}else{
    		return 0;
    	}
    }

    // 从购物车中删除
    public function shopcart_del(Request $request){
    	// dd($request->all());
    	if(DB::table('shopcart')->whereIn('id',$request->ids)->delete()){
    		return 1;
    	}else{
    		return 0;
    	}
    }

    public function shopcart_changenum(Request $request){
    	// return $request->all();
    	if(DB::table('shopcart')->where('id',$request->id)->update($request->all())){
    		return 1;
    	}else{
    		return 0;
    	}
    }

    // 购物车结算 、直接购买
    public function udai_shopcart_pay(Request $request){
    	// dd($request->all());
    	if($request->method){
    		// 直接购买
    		$goods=DB::table('goods')->join('goodssize','goodssize.gid','=','goods.id')->where([['goods.id',$request->gid],['goodssize.color',$request->color],['goodssize.size',$request->size]])->select('goods.id as gid','goodssize.id as sid','name','goods.img','price','color','size')->get();
    		$goods[0]->num=$request->num;
    		// dd($goods);
    		$total=$goods[0]->price*$request->num;
    	}else{
    		// 购物车结算
    		$goods=DB::table('shopcart')->join('goodssize','shopcart.sid','=','goodssize.id')->join('goods','goodssize.gid','=','goods.id')->where('uid',session('uid'))->whereIn('shopcart.id',$request->ids)->select('shopcart.id as shopcartid','goodssize.gid','goodssize.id as sid','name','goods.img','price','color','size','num')->get();
	    	$total=DB::table('shopcart')->join('goodssize','shopcart.sid','=','goodssize.id')->join('goods','goodssize.gid','=','goods.id')->where('uid',session('uid'))->whereIn('shopcart.id',$request->ids)->selectRaw('sum(price * num) as total')->value('total');
    	}
    	$address=DB::table('shipping')->where('uid',session('uid'))->get();
    	return view('index/Shopcart/udai_shopcart_pay',['goods'=>$goods,'total'=>$total,'address'=>$address]);
    }
}
